import { Component } from '@angular/core';
import { NavController,NavParams } from 'ionic-angular';
import { InfoPage } from './window/info';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';

declare var BMap;
//declare var BMapLib;
var map:any;
var myme:any;
@Component({
  selector: 'page-map',
  templateUrl: 'map.html',
})

export class MapPage {
  refreshInterval = 3000;
  refreshTask: any;
  user: any = {};
  public allpersons: any;
  person:any;

  personName:any;
  personAddr:any;
  personArea:any;

  myGeo:any;
  myIcon:any;
 // markerClusterer:any;
  // id: any;
  // personId = null;
  constructor(
    private navCtrl: NavController,
    private rest: RestService,
    public translate: TranslateService,
    public navParams: NavParams,
   // private geolocation: Geolocation
  ) {
    this.user = this.rest.getUser();
    this.allpersons = navParams.data.persons;
    this.myIcon = new BMap.Icon("assets/icon/favicon.ico", new BMap.Size(32, 32));
    myme = this;

  }

  ionViewDidLoad() {

    //Amin: !Important:map_container shoud be called here, it can't be inited in constructor, if called in constructor

    map = new BMap.Map("mapContainer",{ enableMapClick: false });
    map.setMapStyle({
      styleJson:"/assets/custom_map_config.json"
      }
    );

    map.centerAndZoom('青岛', 11);

    map.enableScrollWheelZoom(true);

   // this.myGeo = new BMap.Geocoder();

  //  var geolocationControl = new BMap.GeolocationControl();

  //  this.map.addControl(geolocationControl);
   // this.getLocation();
    this.getDevices();

  }
  /*
  getLocation() {
    console.log(this.person);
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
      console.log(r.point)
      if(this.getStatus() == true){
        var mk = new BMap.Marker(r.point);
        this.map.addOverlay(mk);//标出所在地
        this.map.panTo(r.point);//地图中心移动
        console.log('您的位置：'+r.point.lng+','+r.point.lat);
        var point = new BMap.Point(r.point.lng,r.point.lat);//用所定位的经纬度查找所在地省市街道等信息
        var gc = new BMap.Geocoder();
        gc.getLocation(point, function(rs){
          var addComp = rs.addressComponents; console.log(rs.address);//地址信息
          console.log("my gps");
          console.log(rs);
          console.log(rs.address);//弹出所在地址
          let marker = new BMap.Marker(rs.address.H, {icon: this.myIcon});

          map.panTo(rs.address);

          marker.setPosition(rs.address);

          map.addOverlay(marker);
        //  this.map.centerAndZoom(locationPoint, 13);
        });
      }else {
        console.log('failed'+this.getStatus());
      }
    },{enableHighAccuracy: true});
  }*/
  nav2detail(){
    this.navCtrl.push(InfoPage,{
      person: this.person,
      persons: this.allpersons
    });
  }
  closeDiv(){
    var upmapdiv = document.getElementById('up-map-div');
    //console.log(upmapdiv);
    upmapdiv.setAttribute('style', 'width:100%;height: 150px;display:none;');
  }
 addClickHandler(personId,marker){
   this.rest.get('/data/person/' + personId).subscribe(data => {
     this.person = data;

     this.personName = this.person.personName;
     this.personAddr = this.person.address;
     this.personArea = this.person.bedString;
     var upmapdiv = document.getElementById('up-map-div');
     //console.log(upmapdiv);
     upmapdiv.setAttribute('style', 'width:100%;height: 150px;');//display:none;');
   });

   //this.getPeseronInfo(personId);
  }
  getPeseronInfo(id){
    this.rest.get('/data/person/' + this.person.id).subscribe(data => {
      this.person = data;

      this.personName = this.person.personName;
      this.personAddr = this.person.address;
      this.personArea = this.person.bedString;
    });
    /*for(var i=0;i<this.allpersons.length;i++){
      var curPerson =this.allpersons[i];
      if (curPerson.id==id){
        return curPerson;

      }
    }*/
  }
  getDevices(){
   // console.log(this.allpersons);
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
//https://192.168.123.235/data/device/search/allTypes?institutionId=1&page=0&size=25&sort=deviceId,asc&deviceType=20%25
   // this.rest.get('/api/influx/getCoordinateByPersonId?personId=' + this.person.id).subscribe(data => {
    this.rest.getWithParams('/data/device/search/allTypes', {
      institutionId: this.user.instId,
    //  page:0,
    //  size:50,
     // sort:'deviceId,asc',
      deviceType: "20%"
    }).subscribe(data => {
     // console.log(data);
      data['_embedded']['devices'].forEach(device => {
       // console.log(device.personId);
        this.rest.get('/api/influx/getCoordinateByPersonId?personId=' + device.personId).subscribe(data => {
          if(data!=null) {
            this.addMapMaker(data[2], data[3], device.personId);
          }
        },message=>{
          console.error('Failed to get Coordinate By PersonId in: ' + message);
        });
      });

    },message=>{
      console.error('Failed to get all devices: ' + message);
    });
  }

  addMapMaker(lng,lat,personId){

   // console.log('您的位置：'+lng+','+lat);
    var point = new BMap.Point(lng,lat);//用所定位的经纬度查找所在地省市街道等信息


    var convertor = new BMap.Convertor();
    var pointArr = [];
    pointArr.push(point);

   convertor.translate(pointArr, 1, 5, function (data) {
    // console.log(myme);
      if(data.status === 0) {

        var size = new BMap.Size(16, 16);
        var offset = new BMap.Size(0, -7);
        var imageSize = new BMap.Size(16, 16);
        var icon = new BMap.Icon("/assets/imgs/position.png", size, {
          imageSize: imageSize
        });
        var marker = new BMap.Marker(data.points[0],{
          icon: icon,
          offset: offset
        });

        marker.addEventListener("click",function(e){
          myme.addClickHandler(personId,marker);

        });
        map.addOverlay(marker);
      }
    });
    //  }, 1000);

  }
    refresh() {
    // this.rest.getWithParams('/data/device/search/deviceId', {
    //   deviceId: "01CH000015"
    // }).subscribe(resp => {
    //   this.personId = resp['_embedded']['devices'][0].personId;
    //   this.rest.getWithParams('/data/person/search/id', {
    //     id: this.personId
    //   }).subscribe(resp => {
    //     this.person = resp['_embedded']['persons'][0];
    //   }, message => {
    //     console.error('Failed to get all persons in: ' + message);
    //   });
    // }, message => {
    //   console.error('Failed to get all persons in: ' + message);
    // });
  }

  ngOnInit() {
    // this.refresh();
    // this.refreshTask = setInterval(() => {
    //   this.refresh();
    // }, this.refreshInterval);
  }

  ngOnDestroy() {
    if (this.refreshTask) {
      clearInterval(this.refreshTask);
    }
  }

  navBack() {
    this.navCtrl.pop();
  }
}
